import styles from './create.less';
import { useIntl, useLocation, getLocale } from 'umi';
import { useState, useEffect } from 'react';
import {
  Form,
  Input,
  Select,
  Button,
  Space,
  Upload,
  message,
  DatePicker,
} from 'antd';
import { UploadOutlined, CloseOutlined } from '@ant-design/icons';
const { Dragger } = Upload;
const { TextArea } = Input;
const { Option } = Select;
import request from '@/utils/request';
import config from '@/config/index';
import { getToken } from '@/utils/auth';
import { isImage } from '@/utils';
import moment from 'moment';
import ShortcutOptions from '@/pages/components/shortcutOptions';

let state: string = '';

const campaignsCreate = () => {
  const locale = getLocale();
  const intl = useIntl();
  const [form] = Form.useForm();
  const ulocation = useLocation();

  const types = {
    '1': 'campaign',
    '2': 'template',
  };
  const controllerName = types[ulocation.query.type];

  const [rosterList, setRosterList] = useState([
    {
      id: Number,
      rosterName: String,
      totalPeople: Number,
    },
  ]);

  const [template, setTemplate] = useState({});

  const [fileList, setFileList] = useState([]);

  const [content, setContent] = useState('');

  const [schedule, setSchedule] = useState('');

  const [rosterTotal, setRosterTotal] = useState(0);

  useEffect(() => {
    getRoster();
  }, []);

  useEffect(() => {
    if (ulocation.query.id) {
      getCampaign();
    }
  }, [ulocation.query.id]);

  const getCampaign = () => {
    request.get(`/${controllerName}/${ulocation.query.id}`).then((res) => {
      let data = {
        title: '',
        recipientsList: [],
        schedule: '',
        sendTime: '',
        content: '',
        attachmentList: [],
      };
      if (ulocation.query.type === '1') {
        const { campaign = {} } = res.data;
        const { template = {} } = campaign;
        data = template;
      } else if (ulocation.query.type === '2') {
        const { template = {} } = res.data;
        data = template;
      }
      setTemplate(data);
      const formData = {
        title: data.title,
        recipients:
          (data.recipientsList && data.recipientsList.map((n) => n.rosterId)) ||
          [],
        schedule: data.schedule,
        sendTime: data.sendTime ? moment(data.sendTime) : null,
      };

      form.setFieldsValue(formData);
      setSchedule(data.schedule);
      setContent(data.content);
      setFileList(data.attachmentList || []);
    });
  };

  const getRoster = () => {
    request.get('/roster/get').then((res) => {
      setRosterList(res.data.rosterList);
    });
  };

  const onChangeContent = (e: any) => {
    setContent(e.target.value);
  };

  // 保存和发送  state: D 是保存  !state是发送
  const onSend = (s: string) => {
    state = s;
    form.submit();
  };

  const onFinish = (values: any) => {
    console.log(values);
    const formData = { ...values };
    if (formData.sendTime) {
      formData.sendTime = moment(formData.sendTime).format(
        'YYYY-MM-DD HH:mm:ss',
      );
    }
    const data = {
      ...formData,
      state:
        state || formData.schedule === 'R'
          ? 'O'
          : formData.schedule === 'I'
          ? 'C'
          : '',
      // state:D（草稿）O（待发送）C(已发送)
      // titile: 'titile', //标题
      // schedule: 'Regularly', //Regularly定时发送  、Immediately立刻发送
      // sendTime: '2021-11-27 15:00:00', //定时发送时间 立刻发送没有
      content, //内容
      attachment: fileList, // 附件的url路径
      // recipients: [1, 2, 3], //名单id
    };
    let method = 'post',
      url = `/campaign/create`;
    if (state === 'D') {
      url = `/template/create`;
    }
    if (ulocation.query.id) {
      method = 'post';
      url = `/campaign/create`;
      if (state === 'D') {
        method = 'patch';
        url = `/template/edit`;
      }
    }
    if (template.id) {
      data.templateId = template.id;
    }
    if (!data.title) {
      message.error('please input title');
      return;
    }
    if (!data.recipients || !data.recipients.length) {
      message.error('please select roster');
      return;
    }
    console.log(data);
    request({
      url,
      method,
      data,
    }).then((res) => {
      history.back();
    });
  };

  const [uploadFileList, setUploadFileList] = useState([]);

  const uploadProps = {
    name: 'file',
    multiple: true,
    action: config.baseURL + '/system/fileUpload',
    showUploadList: false,
    // fileList: uploadFileList,
    headers: {
      'Access-Token': getToken(),
    },
    onChange(info: any) {
      console.log('uploadProps.onChange', info);
      const { file, flist } = info;
      if (file.status !== 'uploading') {
        console.log(file, flist);
      }
      console.log('file.status', file.status);
      if (file.status === 'done') {
        const { data } = file.response;
        setFileList([
          ...fileList,
          {
            url: data.url,
            fileName: data.fileName,
            type: data.type,
          },
        ]);
        // setUploadFileList(fileList);
      } else if (file.status === 'error') {
        message.error(`${file.name} file upload failed.`);
      }
    },
  };

  const onRemoveFile = (i: number) => {
    const fl = [...fileList];
    fl.splice(i, 1);
    setFileList(fl);
    // const ufl = [...uploadFileList];
    // ufl.splice(i, 1);
    // setUploadFileList(ufl);
  };

  const onChangeDatePicker = (date: any, dateStr: string) => {};

  // 选择快捷回复
  const onSelectShortcut = (type: string) => {
    setContent(`${content}{{${type}}}`);
  };

  const onChangeSchedule = (e: string) => {
    setSchedule(e);
  };

  const onChangeSelectRoster = (e) => {
    const tp: any = rosterList.filter(
      (n) => e.findIndex((m) => m === n.id) >= 0,
    );
    let tpnum = 0;
    tp.forEach((n) => {
      tpnum += n.totalPeople;
    });
    setRosterTotal(tpnum);
  };

  return (
    <div className={styles.campaignsCreate}>
      <div className={styles.ccleft}>
        <Button onClick={() => history.back()} style={{ marginBottom: 20 }}>
          {intl.formatMessage({ id: 'goBack' })}
        </Button>
        <Form form={form} layout="vertical" onFinish={onFinish}>
          <Form.Item
            label={intl.formatMessage({ id: 'title' })}
            name="title"
            rules={[
              {
                required: true,
                message: intl.formatMessage({
                  id: 'p_i_title',
                }),
              },
            ]}
          >
            <Input placeholder={intl.formatMessage({ id: 'p_i_title' })} />
          </Form.Item>
          <Form.Item
            label={intl.formatMessage({ id: 'messagereceivedcontact' })}
            name="recipients"
            extra={`${intl.formatMessage({
              id: 'messagereceivedcontact',
            })}: ${rosterTotal}`}
            rules={[
              {
                required: true,
                message: intl.formatMessage({
                  id: 'p_i_roster',
                }),
              },
            ]}
          >
            <Select
              mode="multiple"
              placeholder={intl.formatMessage({ id: 'p_s_roster' })}
              onChange={onChangeSelectRoster}
            >
              {rosterList.map((n) => (
                <Option key={n.id} value={n.id}>
                  {n.rosterName}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            label={intl.formatMessage({ id: 'schedulemessagetime' })}
            name="schedule"
            rules={[
              {
                required: true,
                message: intl.formatMessage({
                  id: 'p_i_schedule',
                }),
              },
            ]}
          >
            <Select
              placeholder={intl.formatMessage({ id: 'schedulemessagetime' })}
              onChange={onChangeSchedule}
            >
              <Select.Option value="I">
                {intl.formatMessage({ id: 'sendimmediately' })}
              </Select.Option>
              <Select.Option value="R">
                {intl.formatMessage({ id: 'SpecifyaDateandTime' })}
              </Select.Option>
            </Select>
          </Form.Item>
          {schedule === 'R' ? (
            <Form.Item
              label={intl.formatMessage({ id: 'date_time' })}
              name="sendTime"
              rules={[
                {
                  required: true,
                  message: intl.formatMessage({
                    id: 'p_i_sendTime',
                  }),
                },
              ]}
            >
              <DatePicker
                showTime
                showNow={false}
                format="YYYY-MM-DD HH:mm"
                onChange={onChangeDatePicker}
                style={{ width: '100%' }}
                locale={locale}
              />
            </Form.Item>
          ) : null}

          {/* <Form.Item
            label={intl.formatMessage({ id: 'sendatestmessage' })}
            extra={intl.formatMessage({ id: 'sendatestmessage_extra' })}
            name='schedule'
          >
            <Select
              placeholder={intl.formatMessage({ id: 'sendatestmessage' })}
            >
            </Select>
          </Form.Item> */}
          {/* <Form.Item>
            <Button disabled>{intl.formatMessage({ id: 'send' })}</Button>
          </Form.Item> */}
        </Form>
      </div>
      <div className={styles.ccright}>
        <div className={styles.head}>
          <span />
          <Space>
            <Button onClick={() => onSend('D')}>
              {intl.formatMessage({ id: 'save' })}
            </Button>
            <Button type="primary" onClick={() => onSend('')}>
              {intl.formatMessage({ id: 'send' })}
            </Button>
          </Space>
        </div>
        <div className={styles.uploadCon}>
          <Dragger {...uploadProps}>
            <div className={styles.uploadDragCon}>
              <Button className={styles.uploadbtn}>
                {intl.formatMessage({ id: 'addfile' })}
              </Button>
              <UploadOutlined />
              <p>{intl.formatMessage({ id: 'uploadtext' })}</p>
            </div>
          </Dragger>
        </div>
        {fileList.length ? (
          <div className={styles.fileList}>
            {fileList.map((n, i) => (
              <div
                key={i}
                className={`${styles.fileItem} ${
                  !isImage(n.type) ? styles.file : ''
                }`}
              >
                {isImage(n.type) ? (
                  <img className={styles.img} src={n.url} alt="" />
                ) : (
                  <span className={styles.filename}>{n.fileName}</span>
                )}
                <CloseOutlined
                  className={styles.closeicon}
                  onClick={() => onRemoveFile(i)}
                />
              </div>
            ))}
          </div>
        ) : null}
        <div className={styles.content}>
          <div className={styles.desc}>
            <TextArea
              placeholder={intl.formatMessage({ id: 'compaigntextareamsg' })}
              className={styles.descTextarea}
              value={content}
              onChange={onChangeContent}
            />
          </div>
          <ShortcutOptions onSelect={onSelectShortcut} />
        </div>
      </div>
    </div>
  );
};
campaignsCreate.title = '营销群发讯息设定';

export default campaignsCreate;
